<template>
  <div class="dashboard-editor-container">
    <h3 style="padding-left: 32px">付款流程</h3>
    <el-steps :active="active" align-center finish-status="process">
      <el-step
        title="出账"
        description="正常情况下，每月第5~8个工作日产出上月收入。"
      ></el-step>
      <el-step
        title="上传发票"
        description="如果收入达到最低出账限额并处于每月结算状态，则需要您按照合同约定的开票项目开具正确的增值税发票并上传电子版。"
      ></el-step>
      <el-step
        title="邮寄发票"
        description="邮寄地址为：北京市昌平区七北路69号北京华文学院 高平 13581573399。"
      ></el-step>
      <el-step title="付款" description="发票审核通过后将为您付款。"></el-step>
    </el-steps>
    <div
      style="width: 100%; height: 30px; background: #f2f4f8; margin-top: 25px"
    ></div>
    <h3 style="padding-left: 32px; padding-top: 30px">付款记录</h3>
    <el-form :inline="true" style="margin-top: 30px" label-width="120px">
      <el-form-item label="月份">
        <el-date-picker
          v-model="date"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          format="yyyy-MM"
          value-format="yyyy-MM"
        ></el-date-picker>
      </el-form-item>
      <el-button
        type="primary"
        icon="el-icon-search"
        size="mini"
        @click="getSupplierBillList"
        >搜索</el-button
      >
    </el-form>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 95%; margin: 0px auto"
    >
      <el-table-column label="月份" align="center">
        <template slot-scope="scope"
          >{{ scope.row.year }}.{{ scope.row.month }}</template
        >
      </el-table-column>
      <el-table-column
        prop="predictPrice"
        label="预估收入（元）"
        align="center"
        :formatter="formatterTable"
      >
      </el-table-column>
      <el-table-column
        prop="actualPrice"
        label="实收金额（元）"
        align="center"
        :formatter="formatterTable"
      ></el-table-column>
      <el-table-column
        label="付款状态"
        align="center"
        :formatter="formatterTable"
      >
        <template slot-scope="scope">
          <span v-show="scope.row.processState == '6'">已结算</span>
          <span
            v-show="
              scope.row.processState != '6' &&
              (!scope.row.processState || scope.row.processState == '1')
            "
            >未出账</span
          >
          <span
            v-show="
              scope.row.processState != '6' &&
              (scope.row.processState == '2' ||
                scope.row.processState == '3' ||
                scope.row.processState == '4')
            "
            >待支付</span
          >
          <span v-show="scope.row.processState == '5'">已支付</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            v-show="
              scope.row.processState != '6' &&
              (scope.row.processState == '2' ||
                scope.row.processState == '1' ||
                !scope.row.processState)
            "
            :type="scope.row.processState != '2' ? 'info' : 'success'"
            plain
            :disabled="scope.row.processState != '2'"
            @click="changeEditInvoice(scope.row)"
            >上传发票</el-button
          >
          <el-button
            size="mini"
            v-show="
              scope.row.processState == '3' && scope.row.processState != '6'
            "
            :type="scope.row.processState != '3' ? 'info' : 'success'"
            plain
            :disabled="scope.row.processState != '3'"
            @click="changeEditInvoice(scope.row)"
            >修改发票</el-button
          >
          <el-button
            size="mini"
            type="primary"
            plain
            v-show="
              scope.row.processState != '6' &&
              (scope.row.processState == '4' || scope.row.processState == '5')
            "
            @click="changeViewInvoice(scope.row)"
            >查看发票</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      :page.sync="pageNum"
      :limit.sync="pageSize"
      :pageCount="5"
      @pagination="getSupplierBillList"
    />
    <el-dialog :visible.sync="dialogVisible" width="70%">
      <h3>发票寄出信息</h3>
      <div class="tips">
        <p>温馨提示：</p>
        <p>1.请您完整填写以上全部信息，以便能顺利获得结算金额；</p>
        <p>
          2.公司名称需与发票章、聚峰后台信息一致，否则可能会导致您无法收到结算金额；当发票需要退换时，客服会根据您填写的地址邮寄给您，请您确保信息正确无误。
        </p>
      </div>
      <el-form
        :model="form"
        class="form"
        label-position="right"
        ref="form"
        label-width="auto"
      >
        <el-form-item class="item" label="出账日期：">
          <span>{{ form.billDate }}</span>
        </el-form-item>
        <el-form-item class="item" label="支付金额：">
          <span>{{ form.payPrice }}</span>
        </el-form-item>
        <el-form-item class="item" label="用户名：">
          <span>{{ form.operationUserName }}</span>
        </el-form-item>
        <el-form-item class="item" label="企业名称：">
          <span>{{ form.enterpriseName }}</span>
        </el-form-item>
        <el-form-item
          class="item"
          prop="contactName"
          label="联系人："
          :rules="[
            { required: true, message: '联系人不能为空', trigger: 'blur' },
          ]"
        >
          <el-input
            :disabled="state == 1"
            v-model="form.contactName"
            class="input"
          />
        </el-form-item>
        <el-form-item
          class="item"
          prop="mailingAddress"
          label="邮寄地址："
          :rules="[
            { required: true, message: '邮寄地址不能为空', trigger: 'blur' },
          ]"
        >
          <el-input
            :disabled="state == 1"
            v-model="form.mailingAddress"
            class="input"
          />
        </el-form-item>
        <el-form-item
          class="item"
          label="电话："
          prop="contactPhone"
          :rules="[
            { required: true, message: '电话不能为空', trigger: 'blur' },
          ]"
        >
          <el-input
            :disabled="state == 1"
            v-model="form.contactPhone"
            class="input"
          />
        </el-form-item>
        <el-form-item
          class="item"
          label="发票张数："
          prop="invoiceNum"
          :rules="[
            { required: true, message: '发票张数不能为空', trigger: 'blur' },
          ]"
        >
          <el-input
            :disabled="state == 1"
            v-model="form.invoiceNum"
            class="input"
          />
        </el-form-item>
      </el-form>
      <div>
        <span
          style="
            margin-left: 35px;
            font-weight: 700;
            color: #606266;
            float: left;
          "
          >上传发票：</span
        >
        <el-upload
          v-show="state == '0'"
          style="margin-left: 10%"
          class="avatar-uploader"
          action
          ref="upload"
          list-type="picture-card"
          accept=".jpg, .png, .jpeg"
          :auto-upload="true"
          :show-file-list="true"
          :http-request="uploadBannerFile"
          :on-change="changeUrl"
          :file-list="fileList"
          :on-remove="removeFile"
          multiple
          :limit="2"
        >
          <div slot="file" slot-scope="{ file }">
            <el-image
              style="width: 100%; height: 100%"
              :src="file.url"
              v-if="file.url"
            ></el-image>
            <i v-else class="el-icon-upload"></i>
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
          <div class="el-upload__text">
            <i class="el-icon-upload"></i>
            <span>上传图片</span>
          </div>
          <div class="el-upload__tip" slot="tip">
            <p style="color: red">只能上传jpg/png/jpeg文件，且不超过5M</p>
          </div>
        </el-upload>
        <el-image
          v-show="state == '1' || url"
          style="width: 20%; margin-left: 22px"
          :src="url"
        ></el-image>
        <el-button
          v-show="state == '1'"
          style="margin-left: 20px"
          @click.stop="views"
          >查看发票</el-button
        >
        <el-image-viewer
          v-if="showViewer"
          :on-close="closeViewer"
          :url-list="[url]"
        />
      </div>
      <el-button
        type="primary"
        v-show="state == '0'"
        style="
          position: relative;
          width: 120px;
          height: 45px;
          left: 50%;
          margin-left: -60px;
        "
        @click="submit('form')"
        >保存</el-button
      >
    </el-dialog>
  </div>
</template>

<script>
import {
  querySupplierBillPageList,
  queryExternalBillInvoice,
  submitExternalBillInvoice,
} from "@/api/supplier/supplier.js";
export default {
  data() {
    return {
      // 步骤条进度
      active: 4,
      loading: false,
      total: 0,
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      url: "",
      file: {},
      state: -1,
      form: {},
      dialogVisible: false,
      year: "",
      month: "",
      flag: false,
      showViewer: false, // 显示查看器,
      date: [],
      fileList: [],
      disabled: false,
      imgShow: false,
    };
  },
  components: {
    "el-image-viewer": () =>
      import("element-ui/packages/image/src/image-viewer"),
  },
  created() {
    this.getSupplierBillList();
  },
  methods: {
    changeUrl(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.url = "";
    },
    // 查看
    handlePictureCardPreview(file) {
      this.showViewer = true;
      this.url = file.url;
    },
    // 删除
    handleRemove(file) {
      this.url = "";
      this.file = {};
      this.$refs.upload.clearFiles();
    },
    views() {
      this.showViewer = true;
    },
    closeViewer() {
      this.showViewer = false;
    },
    change(e) {
      this.$forceUpdate();
    },
    submit() {
      if (!this.form.contactName) {
        this.$message.warning("请填写联系人");
        return;
      }
      if (!this.form.contactPhone) {
        this.$message.warning("请填写电话");
        return;
      }
      if (!this.form.invoiceNum) {
        this.$message.warning("请填写发票张数");
        return;
      }
      if (!this.form.mailingAddress) {
        this.$message.warning("请填写邮寄地址");
        return;
      }
      let data = {
        year: this.year,
        month: this.month,
        contactName: this.form.contactName,
        contactPhone: this.form.contactPhone,
        mailingAddress: this.form.mailingAddress,
        invoiceNum: this.form.invoiceNum,
      };
      const form = new FormData();
      if (JSON.stringify(this.file) === "{}") {
        form.append("file", "");
      } else {
        form.append("file", this.file);
      }
      form.append(
        "invoice",
        new Blob([JSON.stringify(data)], { type: "application/json" })
      );
      this.$confirm("是否确认提交, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          if (this.flag) {
            this.$message.warning("请勿重复提交");
            return;
          }
          this.flag = true;
          submitExternalBillInvoice(form)
            .then((res) => {
              loading.close();
              this.flag = false;
              if (res.code == 200) {
                this.$message.success("提交成功");
                this.dialogVisible = false;
                this.file = {};
                this.$refs.upload.clearFiles();
                this.form = {
                  contactName: "",
                  mailingAddress: "",
                  contactPhone: "",
                  invoiceNum: "",
                };
              } else {
                this.$message(res.data.msg);
              }
            })
            .catch(() => {
              loading.close();
              this.flag = false;
            });
        })
        .catch(() => {
          this.flag = false;
        });
    },
    removeFile() {
      this.url = "";
      this.file = {};
      this.$refs.upload.clearFiles();
    },
    // 上传图片文件
    uploadBannerFile(params) {
      this.file = params.file;
      let fileType = this.file.type;
      let isImage = fileType.indexOf("image") != -1;
      let isLt5M = this.file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.error("只能上传图片格式png、jpg、jpeg!");
        return;
      }
      if (!isLt5M) {
        this.$message.error("只能上传图片大小小于5M");
        return;
      }
    },
    // 修改发票
    changeEditInvoice(row) {
      this.dialogVisible = true;
      this.year = row.year;
      this.month = row.month;
      this.state = 0;
      this.getExternalBillInvoice();
    },
    // 查看发票
    changeViewInvoice(row) {
      this.state = 1;
      this.dialogVisible = true;
      this.year = row.year;
      this.month = row.month;
      this.getExternalBillInvoice();
    },
    getExternalBillInvoice() {
      queryExternalBillInvoice({
        year: this.year,
        month: this.month,
      })
        .then((res) => {
          this.url = res.data.invoiceUrl
            ? "/invoice/" + res.data.invoiceUrl
            : "";
          this.form = {
            billDate: res.data.billDate,
            payPrice: res.data.payPrice,
            operationUserName: res.data.operationUserName,
            enterpriseName: res.data.enterpriseName,
            contactName: res.data.contactName,
            mailingAddress: res.data.mailingAddress,
            contactPhone: res.data.contactPhone,
            invoiceNum: res.data.invoiceNum,
          };
        })
        .catch(() => {});
    },
    getSupplierBillList() {
      let str = "";
      let str1 = "";
      if (this.date && this.date.length > 0) {
        str = this.date[0].split("-");
        str1 = this.date[1].split("-");
      }
      this.loading = true;
      querySupplierBillPageList({
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        beginYear: str ? Number(str[0]) : "",
        beginMonth: str ? Number(str[1]) : "",
        endYear: str1 ? Number(str1[0]) : "",
        endMonth: str1 ? Number(str1[1]) : "",
      })
        .then((res) => {
          this.loading = false;
          this.total = res.data.total;
          this.tableData = res.data.list;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 设置无数据是显示--
    formatterTable(row, column, cellValue, index) {
      if (!cellValue && column) {
        if (cellValue == "0") {
          cellValue = "0";
        } else {
          cellValue = "--";
        }
      }
      return cellValue;
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding-top: 10px;
  position: relative;
  overflow: hidden;
  /deep/ .el-upload-dragger {
    width: 400px;
    height: 234px;
    position: relative;
  }
  /deep/ .el-upload-dragger .el-icon-upload {
    margin: 80px 0 16px;
  }

  .tips {
    color: #9c9d9c;
    padding-left: 20px;
    font-size: 14px;
  }
  .form {
    width: 95%;
    height: 100%;
    margin: 0 auto;
    margin-top: 50px;
    overflow: hidden;
    .item {
      width: 50%;
      float: left;
      .input {
        width: 60%;
      }
    }
  }
  .avatar-uploader {
    width: 28%;
    margin-left: 9%;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    border: 1px dashed #d9d9d9;
    width: 600px;
    height: 300px;
    line-height: 300px;
    text-align: center;
    margin-bottom: 20px;
  }
  .avatar {
    width: 300px;
    height: 300px;
    display: block;
  }
}
</style>